/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.evaluation.content.PasswordConditionDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationContentService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 密码应用情况管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class PasswordUseController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private ListView<MenuVO> menuList;
    @FXML
    private VBox phyBox;
    @FXML
    private VBox netBox;
    @FXML
    private VBox deviceBox;
    @FXML
    private VBox appDataBox;

    @FXML
    private TextArea phyEnvEditor;
    @FXML
    private TextArea netCommunicationEditor;
    @FXML
    private TextArea deviceComputeEditor;
    @FXML
    private TextArea appDataEditor;

    private final EvaluationContentService evaluationContentService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;

    public PasswordUseController() {
        this.evaluationContentService = SpringUtils.getBean(EvaluationContentService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        this.initializeMenu();
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerTextChange(this.phyEnvEditor, this.netCommunicationEditor,
                this.deviceComputeEditor, this.appDataEditor);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化密码应用情况信息...");
        this.currentSystemId = systemId;
        this.menuList.getSelectionModel().select(0);
        this.loadPasswordUse();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        if (checkIncomplete()) {
            savePasswordUse(false, false);
        }
    }

    @FXML
    public void onTmpSave() {
        LogUtils.info(log, "执行暂存操作...");
        if (checkIncomplete()) {
            savePasswordUse(false, false);
        }
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        if (checkIncomplete()) {
            this.savePasswordUse(false, true);
        }
    }

    public void realTimeSave() {
        LogUtils.info(log, "执行即时保存操作...");
        if (checkIncomplete()) {
            this.savePasswordUse(true, false);
        }

    }

    private void initializeMenu(){
        this.menuList.setCellFactory(cf->new MenuListCell());
        this.menuList.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if(Objects.nonNull(newValue)){
                        loadContent(newValue);
                    }
                });
        this.menuList.getItems().add(new MenuVO(1,"phyEnv","物理和环境安全",""));
        this.menuList.getItems().add(new MenuVO(2,"netCommunication","网络和通信安全",""));
        this.menuList.getItems().add(new MenuVO(2,"deviceCompute","设备和计算安全",""));
        this.menuList.getItems().add(new MenuVO(2,"appData","应用和数据安全",""));
    }

    private void loadContent(MenuVO menu){
        if(StringUtils.equals(menu.getCode(),"phyEnv")){
            this.appDataBox.setVisible(false);
            this.deviceBox.setVisible(false);
            this.netBox.setVisible(false);
            this.phyBox.setVisible(true);
        } else if(StringUtils.equals(menu.getCode(),"netCommunication")){
            this.phyBox.setVisible(false);
            this.appDataBox.setVisible(false);
            this.deviceBox.setVisible(false);
            this.netBox.setVisible(true);
        } else if(StringUtils.equals(menu.getCode(),"deviceCompute")){
            this.phyBox.setVisible(false);
            this.netBox.setVisible(false);
            this.appDataBox.setVisible(false);
            this.deviceBox.setVisible(true);
        } else if(StringUtils.equals(menu.getCode(),"appData")){
            this.phyBox.setVisible(false);
            this.netBox.setVisible(false);
            this.deviceBox.setVisible(false);
            this.appDataBox.setVisible(true);
        }
    }

    private boolean checkIncomplete(){
        if (StringUtils.isBlank(phyEnvEditor.getText())) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN).withMessage("物理和环境安全密码应用情况不能为空")
                    .build().show();
            return false;
        }
        if (StringUtils.isBlank(netCommunicationEditor.getText())) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN).withMessage("网络和通信安全密码应用情况不能为空")
                    .build().show();
            return false;
        }
        if (StringUtils.isBlank(deviceComputeEditor.getText())) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN).withMessage("设备和计算安全密码应用情况不能为空")
                    .build().show();
            return false;
        }
        if (StringUtils.isBlank(appDataEditor.getText())) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN).withMessage("应用和数据安全密码应用情况不能为空")
                    .build().show();
            return false;
        }
        return true;
    }

    private void loadPasswordUse() {
        LogUtils.info(log, "获取密码应用情况信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.findPasswordCondition(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    this.phyEnvEditor.setText(res.getPhyEnv());
                    this.netCommunicationEditor.setText(res.getNetCommunication());
                    this.deviceComputeEditor.setText(res.getDeviceCompute());
                    this.appDataEditor.setText(res.getAppData());
                }))
                .exceptionally((ex) -> {
                    log.error("获取密码应用情况信息出错!", ex);
                    return null;
                });
    }

    private void savePasswordUse(boolean realTime,boolean finish) {
        PasswordConditionDTO passwordCondition = PasswordConditionDTO.builder()
                .phyEnv(StringUtils.trim(this.phyEnvEditor.getText()))
                .netCommunication(StringUtils.trim(this.netCommunicationEditor.getText()))
                .deviceCompute(StringUtils.trim(this.deviceComputeEditor.getText()))
                .appData(StringUtils.trim(this.appDataEditor.getText()))
                .build();
        LogUtils.info(log, "保存密码应用情况信息...");
        LogUtils.record(log, "请求数据：systemId:{},data:{}", this.currentSystemId, passwordCondition);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService
                        .savePasswordCondition(this.currentSystemId, passwordCondition))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishProcess(finish);
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(realTime){
                            log.error("即时保存失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存密码应用情况信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
        if(prepareView.getController() instanceof PrepareController controller){
            controller.setEvalProcess(EvaluationModule.PASSWORD_USE, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

}